<template>
    <div id="script" class="script-container">
        <div class="script-form script-add">
            <span>脚本名称：</span>
            <el-input v-model="scriptName" style="width:200px;margin-right:10px"></el-input>
            <span>说明：</span>
            <el-input v-model="scriptRemark" style="width:200px;margin-right:10px"></el-input>
            <el-button type="primary" style="margin-right:40px" @click="handleSave">保存</el-button>
            <span>脚本文件：</span>
            <el-upload
                    class="upload-demo"
                    action=""
                    ref="fileRef"
                    show-file-list="true"
                    :limit="2"
                    accept=".py"
                    :on-change="fileChange"
                    :on-remove="handleRemove"
                    :file-list="fileList">
                <el-button type="primary" style="margin-right:10px" v-if="!temp || temp == '{}'">上传</el-button>
                <el-button type="primary" style="margin-right:10px;" v-else>更新</el-button>
            </el-upload>
        </div>
        <div>入参列表：</div>
        <el-table :data="tableData" class="script-table" border @cell-dblclick="cellDblClick">
            <el-table-column type="index" label="序号" align="center" width="80">
            </el-table-column>
            <el-table-column
                    v-for="(item, index) in scriptColumns"
                    :key="index"
                    :prop="item.prop"
                    :label="item.label"
                    align="center"
                    :width="item.width ? item.width : ''"
            >
                <template slot-scope="scope">
                    <div v-if="item.type == 'input'" >
                        <span v-if="!scope.row[item.prop + '$is']" style="cursor: pointer" >{{ scope.row[item.prop] }}</span>
                        <el-input v-if="scope.row[item.prop + '$is']"
                                  v-model="scope.row[item.prop]"
                                  @blur="cellBlur(scope.row, scope.column, scope.$index, item.prop)"
                                  :ref="item.prop">
                        </el-input>
                    </div>
                    <div v-else-if="item.type == 'select'">
                        <el-select v-model="scope.row[item.prop]" placeholder="请选择" @change="selectChanged(scope.row)">
                            <el-option
                                    v-for="item in typeList"
                                    :key="item.dictType"
                                    :label="item.dictName"
                                    :value="JSON.stringify(item)"
                            >
                            </el-option>
                        </el-select>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
                <template slot-scope="scope">
                    <el-button @click="handleDelete(scope.$index)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-button @click="handleAdd" type="primary">添加</el-button>
    </div>
</template>

<script>
    module.exports = {
        props:{
        },
        data: function() {
            return {
                temp:null,
                scriptName:"",
                scriptRemark:"",
                scriptColumns:[
                    {
                        label: '参数名称',
                        prop: 'paramName',
                        type: 'input',
                    },{
                        label: '参数符号',
                        prop: 'paramColumn',
                        type: 'input',
                    },{
                        label: '输入类型',
                        prop: 'inputType1',
                        width: 240,
                        type: 'select',
                    },
                    {
                        label: '说明',
                        prop: 'remark',
                        align: 'center',
                        type: 'input',
                    }
                ],//统计脚本列
                tableData:[],
                typeList:[],
                typeListNo: [
                    {
                        dictType: 'sys_value_import',
                        dictName: '数值输入',
                        typeValue:2
                    },
                    {
                        dictType: 'sys_start_day',
                        dictName: '开始时间(日统计)',
                        typeValue:3
                    },
                    {
                        dictType: 'sys_start_week',
                        dictName: '开始时间(周统计)',
                        typeValue:4
                    },
                    {
                        dictType: 'sys_start_month',
                        dictName: '开始时间(月统计)',
                        typeValue:5
                    },
                    {
                        dictType: 'sys_start_quarter',
                        dictName: '开始时间(季度统计)',
                        typeValue:6
                    },
                    {
                        dictType: 'sys_start_year',
                        dictName: '开始时间(年度统计)',
                        typeValue:7
                    },
                    {
                        dictType: 'sys_end_day',
                        dictName: '结束时间(日统计)',
                        typeValue:3
                    },
                    {
                        dictType: 'sys_end_week',
                        dictName: '结束时间(周统计)',
                        typeValue:4
                    },
                    {
                        dictType: 'sys_end_month',
                        dictName: '结束时间(月统计)',
                        typeValue:5
                    },
                    {
                        dictType: 'sys_end_quarter',
                        dictName: '结束时间(季度统计)',
                        typeValue:6
                    },
                    {
                        dictType: 'sys_end_year',
                        dictName: '结束时间(年度统计)',
                        typeValue:7
                    }
                ],
                fileList: []
            }
        },
        created(){

        },
        mounted(){
            this.handleOption();
        },
        methods: {
            init(){
                this.temp = localStorage.getItem("temp");
                if(this.temp != "{}"){
                    let temp = JSON.parse(this.temp)
                    this.scriptName = temp.name
                    this.scriptRemark = temp.remark
                    $http.get({
                        url:api.scriptListDetails,
                        data:{id:temp.id},
                        success:(result,data)=>{
                            if(data.code == 200){
                                this.tableData = data.data.scriptParamList.map((item)=>{
                                    item.inputType1 = JSON.stringify(this.typeList.filter((obj)=>{return obj.dictType == item.inputType})[0])
                                    return item
                                })
                                this.tableData.sort(function(a,b){return a.id - b.id})
                                console.log(this.tableData)
                                this.fileList= [{
                                    name: data.data.orgName,
                                    url:data.data.storePath
                                }]
                            }
                        },
                        error:(err)=>{

                        }
                    },this)
                    // this.fileList = [{
                    //     name: 'food.jpeg',
                    //     url: ''
                    // }]
                }else {
                    this.tableData = []
                    this.fileList = []
                }
            },
            handleOption(){
                $http.get({
                    url:api.scriptListType,
                    success:(result,data)=>{
                        this.typeList = data.rows.map(item =>{
                            item["typeValue"] = 1
                            return item
                        })
                        this.typeList = [...this.typeListNo, ...this.typeList]
                        // for( var i in this.typeListNo)
                        // {
                        //     this.typeList.push(this.typeListNo[i]);
                        // }
                        this.init();
                    },
                    error:(err)=>{

                    }
                },this)
            },
            handleRemove(file, fileList) {
                let temp = JSON.parse(this.temp)
                $http.get({
                    url:api.scriptDeleteFile,
                    data:{
                        id:temp.id
                    },
                    success:(result,data)=>{
                        if(data.code == 200) {
                            this.$message({
                                type: 'success',
                                message: data.msg
                            });
                            this.fileList = fileList
                        }else {
                            this.fileList = []
                        }
                    },
                    error:(err)=>{

                    }
                },this)
            },
            handlePreview(file) {
                console.log(file);
            },
            fileChange(file, fileList) {

                this.$refs.fileRef.clearFiles()
                if(fileList.length >1){
                    fileList.splice(0,1)
                }

                if(!this.temp || this.temp == '{}'){
                    this.fileList = fileList
                }else {
                    // this.fileList = []

                    this.handleRemove(file, fileList)
                }
            },
            selectChanged(row){
                let inputType1 = JSON.parse(row.inputType1)
                row.typeValue= inputType1.typeValue
                row.inputType = inputType1.dictType
            },
            //双击修改表格内容
            cellDblClick(row, column) {
                this.tableData = this.tableData.filter((item) => {
                    return item;
                });
                this.$set(row, [column.property + "$is"], true);
                this.$nextTick(() => {
                    this.$refs[column.property][0].focus(); // 视图出现后使input获取焦点
                });
            },
            // 可以编辑框失去焦点
            cellBlur(row, column, index, prop) {
                if (row[prop + "-span"]) {
                    let k = row[prop + "-span"].rowspan;
                    this.tableData.forEach((item, i) => {
                        if (i >= index && i < index + k) {
                            item[prop] = row[prop];
                        }
                    });
                }
                row[column.property + "$is"] = false;
            },
            handleAdd(){
                var rowData = {
                    id: "",
                    scId: "",
                    paramName: "",
                    paramColumn: "",
                    inputType: "",
                    inputType1: "",
                    typeValue: "",
                    orderNum: "",
                    remark: ""
                }
                this.tableData.push(rowData)
            },
          handleDelete(index) {
            this.$confirm('此操作将删除该条信息, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.tableData.splice(index,1)
              // this.$message({
              //   type: 'success',
              //   message: '删除成功!'
              // });
            }).catch(() => {
              // this.$message({
              //   type: 'info',
              //   message: '已取消删除'
              // });
            });
          },
          handleSave() {
            if(!this.scriptName) {
              this.$message({
                type: 'info',
                message: '请输入脚本名称'
              });
              return false;
            }
            if(!this.fileList.length) {
              this.$message({
                type: 'info',
                message: '请选择脚本文件'
              });
              return false;
            }
            if(!this.tableData.length) {
              this.$message({
                type: 'info',
                message: '请添加脚本'
              });
              return false;
            }
            let temp = null
            if(this.temp != "{}") {
              temp = JSON.parse(this.temp)
            }

              for(var i=0;i<this.tableData.length;i++){
                  this.tableData[i].orderNum = i+1
              }
              console.log(this.tableData)
            const formdata = new FormData();
            let _raw = this.fileList?.[0].raw
            if(_raw) {
              formdata.set('file', _raw)
            }
            formdata.set('id', temp?.id || '')
            formdata.set('name', this.scriptName)
            formdata.set('remark',this.scriptRemark)
            formdata.set('scriptParams', JSON.stringify(this.tableData))
            $http.post({
              url:api.scriptSave,
              contentType: 'file',
              data:formdata,
              success:(result,data)=>{
                if(data.code == 200) {
                  this.$message({
                    type: 'success',
                    message: data.msg
                  });
                    this.$parent.$parent.activeName = this.$parent.$parent.menuModel = 'script'
                }
              },
              error:(err)=>{

              }
            },this)
          }
        }
    }
</script>

<style scoped>
  .script-container .el-button{
      margin-bottom: 0;
  }
</style>
